#!/usr/bin/env python3

import asyncio
import websockets
import json
import hmac
import hashlib
from datetime import datetime

clients = dict(
    prestoinvt02=dict(
        clientId="X1ppOGCl",
        clientSecret="LcEBG7DIbzbo__DI7Zc8UA7mMZK4qxYDMn7eWTcPlWg"
    ),
    prestoinvt04=dict(
        clientId="WK3PYSiq",
        clientSecret="Qy0vUnB40OjUkbtqjOxmG2uVcAOgOTRMGBAB-el3eoo"
    ),
    prestoinvt05=dict(
        clientId="c6UlD9Bd",
        clientSecret="WRRZJ3xSaGqqqgYSjYFrFVl2_APhl5SohwI0zHPqeKQ"
    )
)
client_name = 'prestoinvt04'
timestamp = round(datetime.now().timestamp() * 1000)
nonce = "abcd"
data = ""
signature = hmac.new(
    bytes(clients[client_name]['clientSecret'], "latin-1"),
    msg=bytes('{}\n{}\n{}'.format(timestamp, nonce, data), "latin-1"),
    digestmod=hashlib.sha256
).hexdigest().lower()

msgs = [
    {
        "jsonrpc": "2.0",
        "id": 8748,
        "method": "public/auth",
        "params": {
            "grant_type": "client_signature",
            "client_id": clients[client_name]['clientId'],
            "timestamp": timestamp,
            "signature": signature,
            "nonce": nonce,
            "data": data
        }
    },
    {
        "jsonrpc": "2.0",
        "id": 2515,
        "method": "private/get_account_summary",
        "params": {
            "currency": "ETH",
            "extended": True
        }
    },
    {
        "jsonrpc": "2.0",
        "id": 2236,
        "method": "private/get_positions",
        "params": {
            "currency": "ETH",
            "kind": "future"
        }
    },
    {
        "jsonrpc": "2.0",
        "id": 22222,
        "method": "private/get_portfolio_margins",
        "params": {
            "currency": "ETH"
        }
    }
]


async def call_api(msgs):
    async with websockets.connect('wss://www.deribit.com/ws/api/v2') as websocket:
        for msg in msgs:
            msg = json.dumps(msg)
            print('----------------------------------------------------------------')
            print(f'Send: {msg}')
            await websocket.send(msg)
            response = await websocket.recv()
            print(f'Recv: {json.dumps(json.loads(response), indent=2)}')
            print('----------------------------------------------------------------')


asyncio.get_event_loop().run_until_complete(call_api(msgs))
